package com.qf.utils.filter;

import com.qf.bean.Employee;
import com.qf.bean.Menu;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.ResourceBundle;

/**
 * IntelliJ IDEA -> person
 * 2019/11/25 16:23
 *
 * @author zmyao
 * 别看，我是渣渣。
 */
public class AuthInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          //授权的前提是：认证之后，及时登录之后
        //先判断是否是匿名地址
        ResourceBundle anon = ResourceBundle.getBundle("anon");
        String requestURI = request.getRequestURI();
        if (anon.containsKey(requestURI)){
            return  true;
        }
        //在判断是否是公共地址
        ResourceBundle publicUrl = ResourceBundle.getBundle("public");
        if (publicUrl.containsKey(requestURI)){
            return  true;
        }
        //在判断该用户是否有该权限
        Employee employee =(Employee) request.getSession().getAttribute("employee");
        List<Menu> menuList = employee.getRole().getMenuList();
        System.out.println("********menuList"+menuList);
        for (Menu menu : menuList) {
            if (requestURI.equals(menu.getUrl())){
                return  true;
            }
            else {
            List<Menu> secondMenus = menu.getSecondMenu();
            for (Menu secondMenu : secondMenus) {
                if (requestURI.equals(secondMenu.getUrl())){
                    return  true;
                }
            }
            }

        }

        //功能请求的判断
        List<Menu> permissionList = employee.getRole().getPermissionList();
        for (Menu permission : permissionList) {
            if (requestURI.equals(permission.getUrl())){
                return  true;
            }
        }

        //授权失败，跳转页面
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("<script>location.href='/error.jsp'</script>");
        return  false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
